package com.sky.controller.admin;


import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.Dishservice;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品分类")
public class DishController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Dishservice dishservice;

    @PostMapping
    public Result savedish(@RequestBody DishDTO dishdto){

        log.info("新增菜品");
        dishservice.save(dishdto);
String key="dish_"+dishdto.getCategoryId();
        redisTemplate.delete(key);
        return Result.success();
    }
    @GetMapping("/page")
    public Result<PageResult> dishPage(DishPageQueryDTO dishpagequeryDTO){
log.info("菜品分页查询");
        PageResult page=dishservice.selectbypage(dishpagequeryDTO);
        return Result.success(page);
    }
@GetMapping("/{id}")
    public Result<DishVO> selectbyid(@PathVariable Long id){
        log.info("根据id查菜品：{}",id);
        DishVO  dishvo=dishservice.selectbyid(id);
        return Result.success(dishvo);
    }
@PutMapping
    public Result updatedish(@RequestBody DishDTO dishdto){
log.info("修改菜品:{}",dishdto);
dishservice.updatedish(dishdto);
    clean("dish_*");
        return Result.success();
    }
    @PostMapping("/status/{status}")
public Result startandstop(@PathVariable Integer status ,Long id){
        log.info("启用或停用商品");
        dishservice.startandstop(status,id);
        clean("dish_*");
        return Result.success();

}
@DeleteMapping
//使用List  Springmvc会自动解析并将逗号分隔，数组就不行
public Result deletedish(@RequestParam List<Long> ids){
        log.info("菜品批量删除:{}",ids);

        dishservice.delteBatch(ids);

clean("dish_*");
return Result.success();
}


public  void clean(String pattern){
    Set keys=redisTemplate.keys(pattern);
    redisTemplate.delete(keys);
}

}
